﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Dir = System.IO.Directory;
using File = System.IO.File;

namespace ComProjectGenerator
{
    class Program
    {
        private static string targetPath = @".\";
        private static string SLN_NAME = "ComProject";
        private static string baseDir = AppDomain.CurrentDomain.BaseDirectory.ToString();
        private static string SLN_GUID = "";
        private static string NM_GUID = "";
        private static string CSPRO_GUID = "";
        private static string COMPRO_GUID = "";
        private static string COMAPI_GUID = "";

        static void Main(string[] args)
        {
            SLN_GUID = Guid.NewGuid().ToString("D");
            NM_GUID = Guid.NewGuid().ToString("D");
            CSPRO_GUID = Guid.NewGuid().ToString("D");
            COMPRO_GUID = Guid.NewGuid().ToString("D");
            COMAPI_GUID = Guid.NewGuid().ToString("D");

            if (args.Length > 1)
            {
                SLN_NAME = args[1];
            }

            if (args.Length > 2) {
                targetPath = args[2];
            }
            if (!Dir.Exists(targetPath)) {
                Dir.CreateDirectory(targetPath);            
            }
            
            DirectoryInfo templateDir=new DirectoryInfo(baseDir+ @"\ComTemplate");
            GenDirFiles(templateDir);        
        }

        /// <summary>
        /// 将字符串A中非标签替换为指定的值
        /// </summary>
        /// <param name="A"></param>
        /// <returns></returns>
        private static string GenFlag(string A) {
            string rs = "";
            rs = A.Replace("*SLN_NAME*", SLN_NAME);
            rs = rs.Replace("*SLN_GUID*", SLN_GUID);
            rs = rs.Replace("*NM_GUID*", NM_GUID);
            rs = rs.Replace("*CSPRO_GUID*", CSPRO_GUID);
            rs = rs.Replace("*COMPRO_GUID*", COMPRO_GUID);
            rs = rs.Replace("*COMAPI_GUID*", COMAPI_GUID);
            return rs;
        }

        private static void GenDirFiles(DirectoryInfo dir) {
            string tmpStr = "";
            foreach (FileInfo fp in dir.GetFiles())
            {
                tmpStr = File.ReadAllText(fp.FullName);
                string fpath = targetPath + @"\" + fp.FullName.Replace(baseDir, "").Replace(".template", "").ToLower().Replace("comtemplate", SLN_NAME);
                string xdir= fpath.Substring(0,fpath.LastIndexOf(@"\"));
                if (!Dir.Exists(xdir)) {
                    Dir.CreateDirectory(xdir);                
                }
                Console.WriteLine("生成: "+ fpath);
                File.WriteAllText(targetPath + @"" + fpath, GenFlag(tmpStr));
            }
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                GenDirFiles(new DirectoryInfo(d.FullName));
            }

        }
    }
}
